var express = require("express");
var router = express.Router();
var Post = require("../../../../models/Post.ts");
const ObjectConfig = require("../../../../models/ObjectConfig.ts"); //拿到总配置信息。
var _ = require("lodash");
var mongodb = require("../../../../models/db.ts");

const getPermisstion = require("../../utils");
const getHost = require("../../Api.ts");
/**查询时间区间数据。
 */
//@Api(name="/rest/fetch/switch/data")
router.post("/fetch/switch/data", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  const body = req.body;
  var startTime = body.startTime;
  var endTime = body.endTime;
  //已经拿到时间戳。
  try {
    ObjectConfig.getObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let allPromise = [];
      //打开数据库
      mongodb.connect((error) => {
        const DataBase = mongodb.db(dataBaseName); // 获取数据库
        _.forEach(configs, (item) => {
          if (getPermisstion(user, `${item.apiKey}_select`)) {
            allPromise.push(
              new Promise((resolve, reject) => {
                DataBase.collection(item.apiKey, function (err, collection) {
                  if (err) {
                  }
                  //查询 updateTime >= startTime 的记录  updateTime <= endTime
                  var query = {
                    updateTime: { $gte: startTime, $lte: endTime },
                  };
                  //根据 query 对象查询文章
                  collection
                    .find(query)
                    .sort({ time: -1 })
                    .toArray(function (err, source) {
                      if (err) {
                      } else {
                        resolve({
                          label: item.name,
                          color: getColor(),
                          icon: item.icon,
                          apiKey: item.apiKey,
                          source,
                        });
                      }
                    });
                });
              })
            );
          }
        });
        Promise.all(allPromise).then((list) => {
          //进行数据封装
          let start = body.startTime;
          let end = body.endTime;
          let min = 24 * 60 * 60 * 1000;
          let data = {
            list: [],
          };
          while (start < end) {
            let sigon = { date: start };
            _.forEach(list, (item) => {
              sigon[item.apiKey] = 0;
            });
            data.list.push(sigon);
            start = start + min;
          }
          _.forEach(list, (item) => {
            data[item.apiKey] = item.source.length;
            data[item.apiKey + "_label"] = item.label;
            data[item.apiKey + "_color"] = item.color;
            data[item.apiKey + "_icon"] = item.icon;
            _.forEach(item.source, (source) => {
              let updateTime = getOriginTime(source.updateTime);
              //拿到查找到的每个数据
              _.filter(data.list, (counts) => {
                var date = new Date(counts.date);
                var time =
                  date.getFullYear() +
                  "-" +
                  (date.getMonth() + 1) +
                  "-" +
                  date.getDate();
                if (updateTime.split(" ")[0] == time) {
                  counts[item.apiKey] = (counts[item.apiKey] || 0) + 1;
                  return true;
                }
              });
            });
          });
          let response = {
            code: 200,
            msg: "OK",
            data: data,
          };
          res.send(response);
        });
      });
    });
  } catch (error) {
    res.send(error);
  }
});

function getOriginTime(time) {
  var date = new Date(time);
  //存储各种时间格式，方便以后扩展
  return (
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1) +
    "-" +
    date.getDate() +
    " " +
    date.getHours() +
    ":" +
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())
  );
}

function getColor() {
  let r = Math.floor(Math.random() * 256);
  let g = Math.floor(Math.random() * 256);
  let b = Math.floor(Math.random() * 256);
  return "#" + r.toString(16) + g.toString(16) + b.toString(16);
}
/**
 * 获取所有数据
 */
//@Api(name="/rest/fetch/all/data")
router.post("/fetch/all/data", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  //已经拿到时间戳。
  try {
    ObjectConfig.getObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let allPromise = [];
      //打开数据库
      mongodb.connect((error) => {
        const DataBase = mongodb.db(dataBaseName); // 获取数据库
        _.forEach(configs, (item) => {
          if (getPermisstion(user, `${item.apiKey}_select`)) {
            allPromise.push(
              new Promise((resolve, reject) => {
                DataBase.collection(item.apiKey, function (err, collection) {
                  if (err) {
                  }
                  //查询 updateTime >= startTime 的记录  updateTime <= endTime
                  var query = {};
                  //根据 query 对象查询文章
                  collection
                    .find(query)
                    .sort({ time: -1 })
                    .toArray(function (err, source) {
                      if (err) {
                      } else {
                        resolve({
                          label: item.name,
                          color: getColor(),
                          icon: item.icon,
                          apiKey: item.apiKey,
                          source,
                        });
                      }
                    });
                });
              })
            );
          }
        });
        Promise.all(allPromise).then((list) => {
          //进行数据封装

          let data = {
            list: [],
          };

          var year = new Date().getFullYear(); //获取今年年份
          let start = 1;
          while (start <= 12) {
            let sigon = { date: year + "-" + start };
            _.forEach(list, (item) => {
              sigon[item.apiKey] = 0;
            });
            data.list.push(sigon);
            start = start + 1;
          }
          _.forEach(list, (item) => {
            data[item.apiKey] = item.source.length;
            data[item.apiKey + "_label"] = item.label;
            data[item.apiKey + "_color"] = item.color;
            data[item.apiKey + "_icon"] = item.icon;
            _.forEach(item.source, (source) => {
              let updateTime = getOriginTime(source.updateTime);
              //拿到查找到的每个数据
              _.filter(data.list, (counts) => {
                if (updateTime.indexOf(counts.date + "-") != -1) {
                  counts[item.apiKey] = (counts[item.apiKey] || 0) + 1;
                  return true;
                }
              });
            });
          });
          let response = {
            code: 200,
            msg: "OK",
            data: data,
          };
          res.send(response);
        });
      });
    });
  } catch (error) {
    res.send(error);
  }
});

//首页展示卡片，获取所有实体信息
//@Api(name="/rest/fetch/cards/data")
router.post("/fetch/cards/data", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  //已经拿到分页数据。
  const body = req.body;
  var page = body.page; //第几页
  var pageSize = body.pageSize; //一页多少？
  var entity = body.entity; //拿到实体apiKey
  var searchKey = body.searchKey; //拿到搜索关键字。
  try {
    ObjectConfig.getObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let allPromise = [];
      //打开数据库
      mongodb.connect((error) => {
        const DataBase = mongodb.db(dataBaseName); // 获取数据库
        if (entity != "all") {
          let item = _.find(configs, (item) => {
            return item.apiKey == entity;
          });
          if (item) {
            allPromise.push(
              new Promise((resolve, reject) => {
                DataBase.collection(item.apiKey, function (err, collection) {
                  if (err) {
                  }
                  //查询 updateTime >= startTime 的记录  updateTime <= endTime
                  var query = {};
                  if (searchKey) {
                    query["name"] = { $regex: searchKey };
                  }
                  //根据 query 对象查询文章
                  collection
                    .find(query)
                    .sort({ time: -1 })
                    .toArray(function (err, source) {
                      if (err) {
                      } else {
                        resolve({
                          label: item.name,
                          icon: item.icon,
                          apiKey: item.apiKey,
                          source,
                        });
                      }
                    });
                });
              })
            );
          }
        } else {
          _.forEach(configs, (item) => {
            if (getPermisstion(user, `${item.apiKey}_select`)) {
              allPromise.push(
                new Promise((resolve, reject) => {
                  DataBase.collection(item.apiKey, function (err, collection) {
                    if (err) {
                    }
                    //查询 updateTime >= startTime 的记录  updateTime <= endTime
                    var query = {};
                    if (searchKey) {
                      query["name"] = { $regex: searchKey };
                    }
                    //根据 query 对象查询文章
                    collection
                      .find(query)
                      .sort({ time: -1 })
                      .toArray(function (err, source) {
                        if (err) {
                        } else {
                          resolve({
                            label: item.name,
                            icon: item.icon,
                            apiKey: item.apiKey,
                            source,
                          });
                        }
                      });
                  });
                })
              );
            }
          });
        }
        Promise.all(allPromise).then((list) => {
          //进行数据封装
          let alldata = [];
          let data = {
            page: page,
            size: pageSize,
            total: 0,
            list: [],
          };

          _.forEach(list, (item) => {
            data.total += item.source.length;
            _.forEach(item.source, (source) => {
              //拿到查找到的每个数据
              alldata.push({
                ...source,
                apiKey: item.apiKey,
                label: item.label,
                icon: item.icon,
                id: source._id,
                tag: item.label + source.name,
                declare: item.label,
              });
            });
          });
          let start =
            (page - 1) * pageSize > alldata.length - 1
              ? alldata.length - 1
              : (page - 1) * pageSize;
          let end =
            page * pageSize > alldata.length ? alldata.length : page * pageSize;
          data.list = _.slice(alldata, start, end);
          let response = {
            code: 200,
            msg: "OK",
            data: data,
          };
          res.send(response);
        });
      });
    });
  } catch (error) {
    res.send(error);
  }
});

//实体之间的关联关系图(这是拿所有实体真实数据之间的关系,单个数据之间的关系很难确定，因为不知道已经关联的实体，是否还继续关联其他实体。)
//@Api(name="/rest/fetch/entity/relation")
router.post("/fetch/entity/relation", (req, res) => {
  let user = req.session.user;
  let dataBaseName = user.company.companyCap + "_service";
  try {
    ObjectConfig.getObjects(dataBaseName, function (err, configs) {
      if (err) {
        configs = [];
      }
      let allPromise = [];
      //打开数据库
      mongodb.connect((error) => {
        const DataBase = mongodb.db(dataBaseName); // 获取数据库

        _.forEach(configs, (item) => {
          if (getPermisstion(user, `${item.apiKey}_select`)) {
            allPromise.push(
              new Promise((resolve, reject) => {
                DataBase.collection(item.apiKey, function (err, collection) {
                  if (err) {
                  }
                  //查询 updateTime >= startTime 的记录  updateTime <= endTime
                  var query = {};
                  //根据 query 对象查询文章
                  collection
                    .find(query)
                    .sort({ time: -1 })
                    .toArray(function (err, source) {
                      if (err) {
                      } else {
                        resolve({
                          label: item.name,
                          icon: item.icon,
                          apiKey: item.apiKey,
                          source,
                          props: item.props,
                          state: item.state,
                        });
                      }
                    });
                });
              })
            );
          }
        });
        Promise.all(allPromise).then((list) => {
          //进行数据封装
          let data = {
            categories: [],
            links: [],
            nodes: [],
          };
          list &&
            list.forEach((item, index) => {
              data.categories.push({ name: item.label });
              let props = item.props ? JSON.parse(item.props) : ""; //拿到字段
              let relProp = _.filter(props, (p) => {
                return p.type == "relation";
              });
              let state = item.state ? JSON.parse(item.state) : ""; //拿到字段
              let relState = _.filter(state, (p) => {
                return p.type == "relation";
              });
              _.forEach(item.source, (source) => {
                //拿到查找到的每个数据
                let hasReletion = false;
                _.forEach(relProp, (prop) => {
                  //有哪些关联内容。
                  let relation = source[prop.apiKey];
                  if (relation) {
                    data.links.push({
                      source: source._id,
                      target: relation.id,
                    });
                    hasReletion = true;
                  }
                });
                _.forEach(relState, (prop) => {
                  //有哪些关联内容。
                  let relation = source[prop.apiKey];
                  if (relation) {
                    data.links.push({
                      source: source._id,
                      target: JSON.parse(relation).id,
                    });
                    hasReletion = true;
                  }
                });
                data.nodes.push({
                  category: index,
                  id: source._id,
                  name: source.name,
                  symbolSize: hasReletion ? 20 : 10,
                  value: item.label + ":" + source.name,
                  x: Math.floor(Math.random() * 2555),
                  y: Math.floor(Math.random() * 2555),
                });
              });
            });
          let response = {
            code: 200,
            msg: "OK",
            data: data,
          };
          res.send(response);
        });
      });
    });
  } catch (error) {
    res.send(error);
  }
});

/**
 * 获取所有图标。
 */
//@Api(name="/rest/fetch/icons")
router.get("/fetch/icons", (req, res) => {
  let response = {
    code: 200,
    msg: "OK",
    data: [
      {
        url: getHost() + "/images/count.svg",
        name: "count",
      },
      {
        url: getHost() + "/images/defaultAvatar.svg",
        name: "defaultAvatar",
      },
      {
        url: getHost() + "/images/sendCount.svg",
        name: "sendCount",
      },
      {
        url: getHost() + "/images/talkCount.svg",
        name: "talkCount",
      },
      {
        url: getHost() + "/images/visitCount.svg",
        name: "visitCount",
      },
      {
        url: getHost() + "/images/iahsb.jpeg",
        name: "iahsb",
      },
      {
        url: getHost() + "/images/iaiem.jpeg",
        name: "iaiem",
      },
      {
        url: getHost() + "/images/ihsfd.jpeg",
        name: "ihsfd",
      },
      {
        url: getHost() + "/images/iiens.jpeg",
        name: "iiens",
      },
      {
        url: getHost() + "/images/ipnwe.jpeg",
        name: "ipnwe",
      },
      {
        url: getHost() + "/images/itimai.jpeg",
        name: "itimai",
      },
      {
        url: getHost() + "/images/inmen.jpeg",
        name: "inmen",
      },
    ],
  };
  res.send(response);
});

module.exports = router;
